package com.wsoft.sms.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsoft.core.annotation.SmsLog;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.CommonFreemarkerService;
import com.wsoft.core.utils.EmailUtil;
import com.wsoft.core.utils.FreemarkerUtil;
import com.wsoft.enums.SendModeEnum;
import com.wsoft.enums.TemplateTypeEnum;
import com.wsoft.sms.entity.SmsTemplateEntity;
import com.wsoft.sms.manager.TemplateManager;
import com.wsoft.sms.mapper.SmsTemplateMapper;
import com.wsoft.sms.query.template.TemplateInsertQuery;
import com.wsoft.sms.query.template.TemplateListQuery;
import com.wsoft.sms.query.template.TemplateTestQuery;
import com.wsoft.sms.query.template.TemplateUpdateQuery;
import com.wsoft.sms.service.ISmsTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;



/**
 * <p>
 * 消息模版 服务实现类
 * </p>
 *
 * @author zhanggukai
 * @since 2024年11月27日 14:31:52
 */
@Service
public class SmsTemplateServiceImpl extends ServiceImpl<SmsTemplateMapper, SmsTemplateEntity> implements ISmsTemplateService , CommonFreemarkerService {
    @Autowired
    private FreemarkerUtil freemarkerUtil;
    @Resource
    private EmailUtil emailUtil;
    @Resource
    private TemplateManager templateManager;
    @Override
    public boolean insert(TemplateInsertQuery query) {
        SmsTemplateEntity entity = Convert.convert(SmsTemplateEntity.class, query);
        if (TemplateTypeEnum.HTML.getCode().equals(entity.getTemplateType())){
            entity.setTemplateContent(HtmlUtil.escape(query.getTemplateContent()));
        }
        QueryWrapper<SmsTemplateEntity> templateWrapper =  new QueryWrapper<>();
        templateWrapper.lambda().eq(SmsTemplateEntity::getTemplateCode, entity.getTemplateCode());
        if (count(templateWrapper)>0){
            Asserts.fail("[sys.code.exist]");
        }
        return save(entity);
    }

    @Override
    public boolean update(TemplateUpdateQuery query) {
        SmsTemplateEntity entity = Convert.convert(SmsTemplateEntity.class, query);
        if (TemplateTypeEnum.HTML.getCode().equals(entity.getTemplateType())){
            entity.setTemplateContent(HtmlUtil.escape(query.getTemplateContent()));
        }
        QueryWrapper<SmsTemplateEntity> templateWrapper =  new QueryWrapper<>();
        templateWrapper.lambda().eq(SmsTemplateEntity::getTemplateCode, entity.getTemplateCode())
                .ne(SmsTemplateEntity::getId, entity.getId());
        if (count(templateWrapper)>0){
            Asserts.fail("[sys.code.exist]");
        }
        return updateById(entity);
    }

    @Override
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public SmsTemplateEntity getTemplate(Long id) {
        return getById(id);
    }

    @Override
    public PageInfo<SmsTemplateEntity> listTemplate(TemplateListQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        QueryWrapper<SmsTemplateEntity> templateWrapper =  new QueryWrapper<>();
        //模板名称
        if (StrUtil.isNotBlank(query.getTemplateName())) {
            templateWrapper.lambda().like(SmsTemplateEntity::getTemplateName, query.getTemplateName());
        }
        //模版编码
        if (StrUtil.isNotBlank(query.getTemplateCode())) {
            templateWrapper.lambda().eq(SmsTemplateEntity::getTemplateName, query.getTemplateCode());
        }
        //模版类型
        if (StrUtil.isNotBlank(query.getTemplateType())) {
            templateWrapper.lambda().eq(SmsTemplateEntity::getTemplateName, query.getTemplateType());
        }
        //模版内容
        if (StrUtil.isNotBlank(query.getTemplateContent())) {
            templateWrapper.lambda().like(SmsTemplateEntity::getTemplateName, query.getTemplateContent());
        }
        return PageInfo.of(list(templateWrapper));
    }

    @Override
    public void sendTest(TemplateTestQuery query) {
        SmsTemplateEntity template = getTemplate(query.getId());
            Map<String, Object> params = new HashMap<>();
            JSONObject jsonObject = new JSONObject(query.getDataModelJson());
            for (String key : jsonObject.keySet()) {
                params.put(key, jsonObject.get(key));
            }
           String content = null;
            if (TemplateTypeEnum.HTML.getCode().equals(template.getTemplateType())){
                String unescape = HtmlUtil.unescape(template.getTemplateContent());
                content = freemarkerUtil.processTemplate(unescape, params,false);
            }
            else {
                content = freemarkerUtil.processTemplate(template.getTemplateContent(), params,false);
            }
            emailUtil.sendEmail(query.getTo(),template.getTemplateName(), content, template.getTemplateType());
    }

    @Override
    @SmsLog
    public String sendTemplate(String templateCode,String type,String dataModelJson,String to) {
        SmsTemplateEntity template = templateManager.getTemplateByCode(templateCode);
        Map<String, Object> params = new HashMap<>();
        JSONObject jsonObject = new JSONObject(dataModelJson);
        for (String key : jsonObject.keySet()) {
            params.put(key, jsonObject.get(key));
        }
        String content = null;
        if (type.equals(SendModeEnum.EMAIL.getCode())){
                if (TemplateTypeEnum.HTML.getCode().equals(template.getTemplateType())){
                    String unescape = HtmlUtil.unescape(template.getTemplateContent());
                    content = freemarkerUtil.processTemplate(unescape, params,false);
                }
                else {
                    content = freemarkerUtil.processTemplate(template.getTemplateContent(), params,false);
                }
                emailUtil.sendEmail(to,template.getTemplateName(), content, template.getTemplateType());
            //todo 短信与微信发送方式
        }
        return content;
    }

    @Override
    public String sendTextTemplate(String templateCode, Map<String, Object> dataModel, boolean isJob) {
        SmsTemplateEntity template = templateManager.getTemplateByCode(templateCode);
        if (ObjUtil.isEmpty(template)){
            Asserts.fail("[sms.template.not.exist]");
        }
        return freemarkerUtil.processTemplate(template.getTemplateContent(), dataModel ,isJob);
    }
}
